package com.androidhuman.example.mapsv2example;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Layout;
import android.text.Spanned;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.androidhuman.example.mapsv2example.R.drawable;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.ic;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;



public class IntroActivity extends FragmentActivity {

	long backKeyPressedTime;

	SharedPreferences userPrefs;
	SharedPreferences.Editor userPrefsEditor;

	// ///////////////////////////////////////////////////

	LinearLayout all;
	LinearLayout report;
	LinearLayout near;
	LinearLayout map_view;
	
	LinearLayout login_btn;
	LinearLayout register_btn;
	LinearLayout register_btn2;

	LinearLayout btn_woman;
	LinearLayout btn_man;

	ImageView woman;
	ImageView woman_clicked;

	ImageView man;
	ImageView man_clicked;

	LinearLayout bar;
	LinearLayout login_block;
	LinearLayout login_screen;
	LinearLayout register_screen;
	LinearLayout need_login;

	LinearLayout btn_register;

	EditText editLoginTextID;
	EditText editLoginTextPassword;
	LinearLayout btnlogin_ok;

	EditText new_nickname;
	EditText edittextRegisterID;
	EditText edittextRegisterPassword;
	EditText edittextRegisterPasswordCheck;

	View me;
	View letter;
	View rank;
	View question;

	// //////////////////////////////////////////////////

	String[] temp;

	String nickname;
	int sex = 0;
	String account_id = null;
	String password = null;
	String passwordAgain=null;

	int userinfo;

	int check = 0;
	
	View loading;

	// /////////////////////////////////////////////////

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro);

		userPrefs = getSharedPreferences("USER", MODE_PRIVATE);
		userPrefsEditor = userPrefs.edit();
		check = userPrefs.getInt("check", 0);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.permitNetwork().build());

		// ///////////////////////////////////////////////////////
		all = (LinearLayout) findViewById(R.id.all);
		report = (LinearLayout) findViewById(R.id.report);
		near = (LinearLayout) findViewById(R.id.near);
		map_view = (LinearLayout) findViewById(R.id.map_view);

		login_block = (LinearLayout) findViewById(R.id.login_block);
		login_btn = (LinearLayout) findViewById(R.id.login_btn);
		register_btn = (LinearLayout) findViewById(R.id.register_btn);
		register_btn2 = (LinearLayout) findViewById(R.id.register_btn2);

		editLoginTextID = (EditText) findViewById(R.id.login_id);
		editLoginTextPassword = (EditText) findViewById(R.id.login_password);

		btnlogin_ok = (LinearLayout) findViewById(R.id.btnlogin_ok);
		loading = (View) findViewById(R.id.loading);

		btn_woman = (LinearLayout) findViewById(R.id.btn_woman);
		btn_man = (LinearLayout) findViewById(R.id.btn_man);

		woman = (ImageView) findViewById(R.id.woman);
		woman_clicked = (ImageView) findViewById(R.id.woman_clicked);

		man = (ImageView) findViewById(R.id.man);
		man_clicked = (ImageView) findViewById(R.id.man_clicked);

		login_screen = (LinearLayout) findViewById(R.id.login_screen);
		register_screen = (LinearLayout) findViewById(R.id.register_screen);

		btn_register = (LinearLayout) findViewById(R.id.btn_register);

		userinfo = userPrefs.getInt("myID",0);
		
		GhostCharacterShield gcs = new GhostCharacterShield();
		new_nickname = (EditText) findViewById(R.id.register_nickname);
		new_nickname.setFilters(new GhostCharacterShield[]{gcs});
		new_nickname.addTextChangedListener(new cusTextWatcher(new_nickname, 8));
		
		Alpha_Num_OK an =new Alpha_Num_OK();
		edittextRegisterID = (EditText) findViewById(R.id.register_id);
		edittextRegisterID.setFilters(new Alpha_Num_OK[]{an});
		edittextRegisterID.addTextChangedListener(new cusTextWatcher(edittextRegisterID, 10));
		edittextRegisterPassword = (EditText) findViewById(R.id.register_password);
		edittextRegisterPassword.setFilters(new Alpha_Num_OK[]{an});
		edittextRegisterPassword.addTextChangedListener(new cusTextWatcher(edittextRegisterPassword, 12));
		edittextRegisterPasswordCheck = (EditText)findViewById(R.id.register_password_again);
		edittextRegisterPasswordCheck.setFilters(new Alpha_Num_OK[]{an});
		edittextRegisterPasswordCheck.addTextChangedListener(new cusTextWatcher(edittextRegisterPasswordCheck, 12));
		
		bar = (LinearLayout) findViewById(R.id.bar);

		me = (View) findViewById(R.id.me);
		letter = (View) findViewById(R.id.letter);
		rank = (View) findViewById(R.id.rank);
		question = (View) findViewById(R.id.question);

		if (check == 1) {

			login_block.setVisibility(LinearLayout.GONE);
			bar.setVisibility(LinearLayout.VISIBLE);

		}

		// ////////////////////////////////////////////////////////

		report.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				check = userPrefs.getInt("check", 0);

				if (check == 1) {
					Intent intent;
					intent = new Intent(getApplicationContext(),
							ReportActivity.class);
					startActivity(intent);

				} else {
					need_login.setVisibility(LinearLayout.VISIBLE);

				}
			}
		});
		
		map_view.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				loading.setVisibility(LinearLayout.VISIBLE);

				Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {

						loading.setVisibility(LinearLayout.GONE);

					}
				};

				handler.sendEmptyMessageDelayed(0, 2500);

				new Thread(new Runnable() {
					public void run() {

						Intent intent;
						intent = new Intent(getApplicationContext(), MapActivity.class);
						startActivity(intent);

					}
				}).start();

			

			}
		});

		near.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				loading.setVisibility(LinearLayout.VISIBLE);

				Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {

						loading.setVisibility(LinearLayout.GONE);

					}
				};

				handler.sendEmptyMessageDelayed(0, 2500);

				new Thread(new Runnable() {
					public void run() {

						Intent intent;
						intent = new Intent(getApplicationContext(), ListActivity.class);
						intent.putExtra("option_near_or_all", 0);
						startActivityForResult(intent, 1);
					}
				}).start();

			

			}
		});

		all.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				loading.setVisibility(LinearLayout.VISIBLE);

				Handler handler = new Handler() {
					@Override
					public void handleMessage(Message msg) {

						loading.setVisibility(LinearLayout.GONE);

					}
				};

				handler.sendEmptyMessageDelayed(0, 2500);

				new Thread(new Runnable() {
					public void run() {


						Intent intent;
						intent = new Intent(getApplicationContext(), ListActivity.class);
						intent.putExtra("option_near_or_all", 1);
						startActivityForResult(intent, 1);

					}
				}).start();

			}
		});

		login_btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				login_screen.setVisibility(LinearLayout.VISIBLE);

			}
		});

		btnlogin_ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				boolean netOk=false;
				try{
					// TODO Auto-generated method stub
					String strLoginID = editLoginTextID.getText()
							.toString();
					String strLoginPassword = editLoginTextPassword
							.getText().toString();
					boolean isSuccess = false;
					isSuccess = loginCheck(strLoginID, strLoginPassword);
					if (isSuccess) {

					} else {

					}
					netOk=true;
				}
				catch(Exception e){}
				if(!netOk)
				{
					Toast toast = Toast.makeText(
							getApplicationContext(), "인터넷 연결을 확인하세요.",
									Toast.LENGTH_SHORT);
					toast.show();
				}
			}
		});

		register_btn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				register_screen.setVisibility(LinearLayout.VISIBLE);

			}
		});

		register_btn2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				register_screen.setVisibility(LinearLayout.VISIBLE);
				login_screen.setVisibility(LinearLayout.GONE);

			}
		});

		btn_woman.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (woman.getVisibility() == ImageView.VISIBLE) {
					woman.setVisibility(ImageView.GONE);
					woman_clicked.setVisibility(ImageView.VISIBLE);
					man.setVisibility(ImageView.VISIBLE);
					man_clicked.setVisibility(ImageView.GONE);
					sex = 1;
				} else {
					woman.setVisibility(ImageView.VISIBLE);
					woman_clicked.setVisibility(ImageView.GONE);
					sex = 0;

				}

			}
		});

		btn_man.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (man.getVisibility() == ImageView.VISIBLE) {
					man.setVisibility(ImageView.GONE);
					man_clicked.setVisibility(ImageView.VISIBLE);
					woman.setVisibility(ImageView.VISIBLE);
					woman_clicked.setVisibility(ImageView.GONE);
					sex = 2;
				} else {
					man.setVisibility(ImageView.VISIBLE);
					man_clicked.setVisibility(ImageView.GONE);
					sex = 0;

				}

			}
		});

		btn_register.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Register();

			}

		});

		register_screen.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				RegisterClose();

			}
		});

		login_screen.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				login_screen.setVisibility(LinearLayout.GONE);


			}
		});

		me.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(), MeActivity.class);
				startActivity(intent);

			}
		});

		letter.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(),
						LetterActivity.class);
				startActivity(intent);

			}
		});

		rank.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(), RankActivity.class);
				startActivity(intent);

			}
		});

		question.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intent;
				intent = new Intent(getApplicationContext(),
						QuestionActivity.class);
				startActivity(intent);

			}
		});

		// ///////////////////////////////////////////////////////////////////로그인이
		// 필요합니다 화면

		need_login = (LinearLayout) findViewById(R.id.need_login);

		need_login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub

				need_login.setVisibility(LinearLayout.GONE);
			}
		});

	}

	public void Register() {
		nickname = new_nickname.getText().toString();
		account_id = edittextRegisterID.getText().toString();
		password = edittextRegisterPassword.getText().toString();
		passwordAgain = edittextRegisterPasswordCheck.getText().toString();

		if (sex == 0) {

			Toast.makeText(this, "성별을 선택해주세요", Toast.LENGTH_SHORT).show();

		} else if (nickname.length() == 0) {

			Toast.makeText(this, "닉네임을 입력해주세요", Toast.LENGTH_SHORT).show();

		} else if (account_id.length() == 0) {
			Toast.makeText(this, "아이디 입력해주세요", Toast.LENGTH_SHORT).show();
		} else if (password.length() < 4) {
			Toast.makeText(this, "비밀번호가 너무 짧습니다.", Toast.LENGTH_SHORT).show();
		}else if ( !passwordAgain.equals(password))
		{
			Toast.makeText(this, "비밀번호가 서로 일치하지 않습니다.", Toast.LENGTH_SHORT).show();
		}
		else {
			try{
				String response = HttpRequest.get(
						"http://dev.ts.hs.kr/trend/newuser.php", true, 
						"nickname", nickname, 
						"account_id", account_id, 
						"password", password, 
						"sex", sex)
						.body();
				if (response.compareTo("0") == 0) {
					Toast.makeText(this, "성공적으로 가입되었습니다.", Toast.LENGTH_SHORT)
					.show();
				}
				else if(response.compareTo("1") == 0){
					Toast.makeText(this, "이미 있는 별명입니다.", Toast.LENGTH_SHORT).show();
				}
				else if(response.compareTo("2") == 0){
					Toast.makeText(this, "이미 누가 써버린 ID입니다.", Toast.LENGTH_SHORT).show();
				}
				else if(response.compareTo("3") == 0){
					Toast.makeText(this, "이미 누가 써버린 ID와 별명입니다.", Toast.LENGTH_SHORT).show();
				}

				RegisterClose();

				RegisterSuccess(account_id);
				login_screen.setVisibility(LinearLayout.VISIBLE);}

		
			
			catch(Exception e){Toast.makeText(this, "인터넷 연결 오류입니다.", Toast.LENGTH_SHORT)
				.show();}
		}

	}

	// 상단 액션바 아이템 리스너
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:
			break;

		case R.id.item1:
			break;

		case R.id.item2:

			break;
		case R.id.item3:
			break;

		default:
			return false;
		}

		return true;
	}

	public void RegisterClose() {

		register_screen.setVisibility(LinearLayout.GONE);
		sex = 0;
		man.setVisibility(ImageView.VISIBLE);
		man_clicked.setVisibility(ImageView.GONE);
		woman.setVisibility(ImageView.VISIBLE);
		woman_clicked.setVisibility(ImageView.GONE);

		new_nickname.setText("");
		edittextRegisterID.setText("");
		edittextRegisterPassword.setText("");
		edittextRegisterPasswordCheck.setText("");
		

	}
	
	public void RegisterSuccess(String temp) {

	editLoginTextID.setText(temp);

	}

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu, menu);
		getActionBar().setLogo(R.drawable.actionbar_icon);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);
		return true;
	}

	// 뒤로가기 종료 메소드
	public void onBackPressed() {

		Toast toast = null;

		if (login_screen.getVisibility() == LinearLayout.VISIBLE
				|| register_screen.getVisibility() == LinearLayout.VISIBLE
				|| need_login.getVisibility() == LinearLayout.VISIBLE) {
			login_screen.setVisibility(LinearLayout.GONE);
			RegisterClose();
			need_login.setVisibility(LinearLayout.GONE);

		} else {

			if (System.currentTimeMillis() <= backKeyPressedTime + 2000) {

				this.moveTaskToBack(true);
				this.finish();
				android.os.Process.killProcess(android.os.Process.myPid());
				System.exit(0);
			} else {

				backKeyPressedTime = System.currentTimeMillis();

				toast = Toast.makeText(this, "\'뒤로\'버튼을 한번 더 누르시면 종료됩니다.",
						Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}

	public boolean loginCheck(String account_id, String loginpassword) {
		String responselogin = HttpRequest.get(
				"http://dev.ts.hs.kr/trend/userslogin.php", true, "account_id",
				account_id, "password", loginpassword).body();

		if (responselogin.compareTo("1") == 0) {

			Toast.makeText(this, "등록되지 않은 아이디입니다", Toast.LENGTH_SHORT).show();
			return false;
		} else if (responselogin.compareTo("0") == 0) {

			Toast.makeText(this, "잘못된 비밀번호입니다", Toast.LENGTH_SHORT).show();
			return false;
		} else {
			String usersplit[] = responselogin.split("彁");
		

			login_screen.setVisibility(LinearLayout.GONE);
			bar.setVisibility(LinearLayout.VISIBLE);
			login_block.setVisibility(LinearLayout.GONE);

			userPrefsEditor.putInt("myid", Integer.parseInt(usersplit[0]));
			userPrefsEditor.commit();
			userPrefsEditor.putInt("mysex", Integer.parseInt(usersplit[7]));
			userPrefsEditor.commit();
			userPrefsEditor.putString("mynickname", usersplit[1]);
			userPrefsEditor.commit();
			userPrefsEditor.putString("myemail", usersplit[2]);
			userPrefsEditor.commit();
			userPrefsEditor.putInt("check", 1);
			userPrefsEditor.commit();

			return true;
		}
		// return true;
	}

}

